/**
 * Created by Administrator on 13-12-31.
 */
package main

import (
	_ "../test/mysql"
	"database/sql"
	// "encoding/json"
	"bytes"
	"fmt"
	"net/rpc"
	"os"
	"strconv"
	"time"
)

var gerr error

var pClient *rpc.Client

// var db = &sql.DB{}

type Args struct {
	I int
}

const (
	Sql string = "INSERT INTO t_history(ciid,save_time,tag_value,tag_dtype,tag_timestamp,tag_quality,create_time) VALUES"
)

type MyMethod int

type DivResult struct {
	Quo, Rem int
}
type Grid struct {
	Lists []PointGroup
}

type PointGroup struct {
	Ciid  string
	Value string
	Aste  int
	Pv    int
	Time  string
}

var multResult []PointGroup

func AddDatas() {
	db, err := sql.Open("mysql", "fy:fy0123498765@tcp(192.168.1.15:3306)/imhdb?charset=utf8")
	// db, err := sql.Open("mysql", "fy:fy0123498765@tcp(127.0.0.1:3306)/imhdb?charset=utf8")
	checkErr(err)
	// // db, err := sql.Open("mysql", "fy:fy0123498765@tcp(localhost:3306)/imhdb?charset=utf8")
	var buffer bytes.Buffer
	s := strconv.FormatInt(time.Now().Unix(), 10)
	timedate := time.Now().Format("2006-01-02 15:04:05")
	for i, ele := range multResult {
		// fmt.Println(i)
		if i == len(multResult)-1 {
			buffer.WriteString("('" + ele.Ciid + "'," + s + ",0,0,0,-3,'" + timedate + "')")
		} else {
			buffer.WriteString("('" + ele.Ciid + "'," + s + ",0,0,0,-3,'" + timedate + "'),")
		}

	}
	// fmt.Println(Sql + buffer.String())
	result, err := db.Exec(Sql + buffer.String())
	if err != nil {
		fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())
		return
	}
	fmt.Println(result)
	db.Close()
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func init_rpc() {
	if pClient == nil {
		fmt.Println("new rpc")
		pClient, gerr = rpc.Dial("tcp", "127.0.0.1:7777")
		if gerr != nil {
			fmt.Println(gerr)
		}
	}

}

func main() {
	init_rpc()

	t := time.Tick(5 * time.Second)
	for now := range t {
		err := pClient.Call("MyMethod.DataSource", &Args{10000}, &multResult)
		if err != nil {
			fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())
			return
		}
		start := time.Now()
		AddDatas()
		end := time.Now()
		fmt.Println("insert total time:", end.Sub(start).Seconds())
		fmt.Println(now)

	}

}
